import Vue from 'vue'
import Router from 'vue-router'
import Login from '../views/Login.vue'
import Home from '../components/Home.vue'
import NoMatch from '../views/NoMatch.vue'
import FirstPage from '../views/FirstPage.vue'
import User from '../views/User.vue'
import Book from '../views/Book.vue'
import List from '../views/List.vue'
import AddUser from '../views/AddUser.vue'
import AddBook from '../views/AddBook.vue'
import BookList from '../views/BookList.vue'
import BookDetail from '../views/BookDetail.vue'
import UpUserData from '../views/UpUserData.vue'
import ViewUserForm from '../views/ViewUserForm.vue'



Vue.use(Router)

const router = new Router({
  routes: [
    {
      path:'',
      redirect:'/login'
    },
    {
      path: '/login',
      name: 'login',
      component:Login
    },
    {
     path:'/home',
      name:'home',
      component:Home,
      children:[
        {
          path:'/home',
          redirect:'/home/user'
        },
        {
          path:'/home/firstPage',
          component:FirstPage
        },
        {
          path:'/home/user',
          component:User,
          children:[
            {
              path:'/home/user',
              redirect:'list',
              name:'list'
            },
            { 
              path:'list',
              component:List
            },
            {
              path:'addUser',
              component:AddUser,
              name:'addUser',
              // meta: {
              //   keepAlive: true, //此组件需要被缓存
              // }
            },
            {
              path:'bookDetail',
              component:BookDetail,
              name:'bookDetail',
              // meta: {
              //   keepAlive: false, //此组件不需要被缓存
                
              // }
            },
            {
              path:'upUserData',
              component:UpUserData,
              name:'upUserData'
            },
            {
              path:'viewUserForm',
              component:ViewUserForm,
              name:'ViewUserForm'
            }
          ]
        },
        {
          path:'/home/book',
          component:Book,
          children:[
            {path:'/home/book',redirect:'bookList'},
            {path:'bookList',component:BookList},
            {path:'addBook',component:AddBook}

          ]
        }
      ]
    },
    {
      path:'/NoMatch',
      name:'NoMatch',
      component:NoMatch
    },
    {
      path:'*',
      redirect:'/NoMatch'
    }
  ]
})

// 全局守卫 不能写在main.js中 因为此时router已经准备就绪 所以这个守卫不会执行
// 此处路由还未准备就绪 所以可以发挥作用
router.beforeEach((to,from,next) =>{
  let user = localStorage.getItem('user')
  if(to.path!='/login'){
      if(user){
          next()
      }else{
          next({
              path:'/login',
              query:{redirect:to.fullPath}
          })
      }
  }else{
      next()
  }
})

export default router